package cn.edu.sjtu.gateway.filter;

import cn.edu.sjtu.gateway.model.RespStatus;
import cn.edu.sjtu.gateway.util.JWTUtil;
import cn.edu.sjtu.gateway.util.ResultUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;


@Component
public class GlobalAuthenticationFilter implements GlobalFilter, Ordered {

    @Value("#{${auth.skip}}")
    private Map<String, List<String>> skip;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        // skip urls
        String method = exchange.getRequest().getMethodValue();
        String url = request.getURI().getPath();
        if (skip.keySet().contains(method) && skip.get(method).contains(url)) {
            return chain.filter(exchange);
        }
        // verify token
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isEmpty(token)) {
            return ResultUtil.writeError(exchange, RespStatus.NON_TOKEN);
        }
        if (!JWTUtil.verify(token)) {
            return ResultUtil.writeError(exchange, RespStatus.INVALID_TOKEN);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
